const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);

const { Server } = require("socket.io");
var io = new Server(server, { cors: true });

const cors = require("cors");
app.use(cors());
const user = new Map();

io.on("connection", (socket) => {
  socket.on("disconnect", function () {
    console.log(`玩家${user.get(socket.id)}断开`);
    socket.broadcast.emit("off", user.get(socket.id));
    user.delete(socket.id);
  });

  // 将收到的信息广播给所有用户
  socket.on("message", function (data) {

    if (!user.get(socket.id)) connection(socket.id, data.id);
    socket.broadcast.emit("message", data);
  });
});
function connection(socketID, id) {
  user.set(socketID, id);
  console.log("玩家连接: " + id + "|当前在线：" + user.size);
}

//设置跨域访问
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild"
  );
  res.header("Access-Control-Allow-Headers", ["mytoken", "Content-Type"]);
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", " 3.2.1");
  // res.header("Content-Type", "application/json;charset=utf-8");
  res.header("Content-Type", "charset=utf-8");
  next();
});

server.listen(6868, () => {
  console.log("listening on *:6868");
});
